package com.file.system.plugin.validated;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;


public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private String tempBody;

    public MyHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        this.tempBody = getBody(request);
    }

    /**
     * 获取请求体
     *
     * @param request 请求
     * @return 请求体
     */
    private String getBody(HttpServletRequest request) {
        try {
            // 创建一个StringBuilder对象
            StringBuilder stringBuilder = new StringBuilder();
            // 创建一个BufferedReader对象，用于从输入流中读取数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
            String line;
            // 循环读取输入流中的数据，并将其存储到stringBuilder中
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }

            // 将stringBuilder中的数据转换为String类型
            String data = stringBuilder.toString();

            return data;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取请求体
     *
     * @return 请求体
     */
    public String getBody() {
        return tempBody;
    }

    /**
     * 需要重写这个方法
     *
     * @return
     * @throws IOException
     */
    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    /**
     * 需要重写这个方法
     *
     * @return
     * @throws IOException
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {
        // 创建字节数组输入流
        final ByteArrayInputStream bais = new ByteArrayInputStream(tempBody.getBytes(Charset.defaultCharset()));
        // 创建ServletInputStream
        return new ServletInputStream() {
            // 判断是否完成
            @Override
            public boolean isFinished() {
                return false;
            }

            // 判断是否准备好
            @Override
            public boolean isReady() {
                return false;
            }

            // 设置读取监听器
            @Override
            public void setReadListener(ReadListener readListener) {
            }

            // 读取
            @Override
            public int read() throws IOException {
                return bais.read();
            }
        };
    }
}